package com.lntea.security.aes;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class LnteaAES {
	private static String text = "hello lntea security aes";
	
	public static void main(String[] args) {
		jdkAES();
		
		bcAES();
	}
	
	public static void jdkAES(){
		try {
			//generate key
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			keyGenerator.init(128);//128 192 256
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] encodedKey = secretKey.getEncoded();
			
			//key convert
			SecretKey convertSecretKey = new SecretKeySpec(encodedKey, "AES");
			
			//encrypt key
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(text.getBytes());
			System.out.println(new String(Base64.encodeBase64(result)));
			
			//decrypt key
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			System.out.println(new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void bcAES(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			
			//generate key
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES","BC");
			keyGenerator.init(128);
			SecretKey secretKey = keyGenerator.generateKey();
			byte[] encodedKey = secretKey.getEncoded();
			
			//key convert
			SecretKey convertSecretKey = new SecretKeySpec(encodedKey, "AES");
			
			//encrypt key
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(text.getBytes());
			System.out.println(new String(Base64.encodeBase64(result)));
			
			//decrypt key
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			System.out.println(new String(result));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
